
import {message, Modal} from "antd";
import {changeFormLoading, changeFormData} from "./RegForm";
import {changeConditon} from './condition';
import {fetchPosts, addOnePostByAdmin, destoryPost} from '../services/Post';


export const QUERY_LATEST_POSTS = "QUERY_LASTEST_POSTS";
export const SHOW_POSTS = "SHOW_POSTS";
export const ADD_ONE_USER = "ADD_ONE_USER";
export const CHANGE_TABLE_LOADING = "CHANGE_TABLE_LOADING";
export const SHOW_POSTS_FAILED = "SHOW_POSTS_FAILED";
export const GET_ONE_USER = "GET_ONE_USER";



export function deletePost(id){
  return function(dispatch, getState) {
    return destoryPost(id).then(
      () => dispatch(queryLatestPosts(getState().condition)),
      (error) => {
        Modal.error({
          title: '删除失败',
          content: '原则上永远不能够删除用户，您没有超级权限！'+error,
        });
        return;
      }
    );

  }
}

export function getPost(id){
  return function(dispatch, getState){
  }
}


function showPostsFailed(error){
  console.log(error);
}




export function queryLatestPostS(condition){
  return function (dispatch, getState) {
    let page = condition.pagination;
    let pageSize = page.pageSize;
    let skipNumber = pageSize*(page.current-1);
    let total = page.total;
    if (page.current*pageSize >= total && getState().PostS.data.length > 0) {
      total = total + pageSize;
    }
    dispatch(changeConditon({pagination: {
      pageSize:　pageSize,
      total: total,
      current: page.current
    }}));

    dispatch(changeTableLoading(true));
    return fetchPosts({
      descending: "updatedAt",
      limit: pageSize,
      skip: skipNumber
    }).then (
      Posts => dispatch(showPosts(Posts, total)),
      error => dispatch(showPostsFailed(error))
    )
  }
}

function changeTableLoading(isLoading){
  return {type: CHANGE_TABLE_LOADING, isLoading}
}

function showPosts(Posts, total=10){
  return {type: SHOW_POSTS, posts, total}
}
function showPostsFailed(error){
  return {type: SHOW_POSTS_FAILED, error}
}

export function addOnePost(){
  return function (dispatch, getState) {
    dispatch(changeFormLoading(true));
    dispatch(changeTableLoading(true));
    let postData = {
      postname: getState().RegForm.postname.value,
      password: getState().RegForm.password.value,
      email:  getState().RegForm.email.value,
    }
    return addOnePostByAdmin(postData).then (
      posts => {

        dispatch(queryLatestPosts(getState().condition));
        message.success("添加成功！");
        dispatch(changeFormLoading(false));


      },
      error => {
        // message.error(error);
        dispatch(showPostsFailed(error))
      }
    )
  }
}
